const add = (a, b) => a + b;
const sqrt = (a) => a * a;
const res = sqrt(add(1, 2));
const compose =
  (f1, f2) =>
  (...args) => {
    // console.log(args);
    return f2(f1(...args));
  };

const forEachCompose = (...[f1, ...fn]) => {
  return (...agrs) => {
    let res = f1(...agrs);
    fn.forEach((f) => {
      res = f(res);
    });
    return res;
  };
};
const composeReduce = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)))

const result = composeReduce(add, sqrt, sqrt)(1, 2);
const rest2 = forEachCompose(add, sqrt, sqrt)(1, 2);

console.log(res, result, rest2);
let app = {
  arr: [],
  use(fn) {
    this.arr.push(fn);
  },
  compose() {
    // 基本递归实现
    /* const dispatch = (index) => {
      if (index === this.arr.length) return Promise.resolve();
      let mid = this.arr[index];
      return Promise.resolve(mid(() => dispatch(index + 1)));
    };
    return dispatch(0); */
    // 使用reduce实现
    return this.arr.reduce((a, b) => (...args) => {
      return Promise.resolve(a(() => b(...args)));
    })(() => {});
  },
  run() {
    this.compose().then(() => {});
  },
};
app.use((next) => {
  console.log(1);
  next();
});
app.use((next) => {
  console.log(2);
  next();
});
app.use((next) => {
  console.log(3);
  next();
});
app.run();
